<template>
  <div class="bar" ref="bar" @touchstart.stop="prowTouch">
    <div
      class="pro-w"
      ref="prow"
      :style="{ width: barWidth * progress + 'px' }"
    ></div>
    <div
      class="pro-c"
      ref="proc"
      :style="{ left: barWidth * progress + 'px' }"
      @touchstart.stop="startAction"
    ></div>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      prow: 0,
      position: 0,
      barWidth: 0,
    };
  },
  computed: {
    ...mapState({
      progress: (state) => state.player.progress,
      duration:(state) => state.player.duration,
      currentTime:state=>state.player.currentTime
    }),
  },
  mounted() {
    this.barWidth = this.$refs.bar.offsetWidth;
    this.position = this.barWidth * this.progress;
    this.$refs.proc.style.left = this.barWidth * this.progress + "px";
  },
  watch:{
    progress(newVal){
      this.position = this.barWidth * newVal;
    }
  },
  methods: {
    // 进度条点击
    prowTouch(e){
      let offLeft=(document.documentElement.offsetWidth-this.barWidth)/2
      let offset=e.changedTouches[0].clientX-offLeft
      offset<0&& (offset=0)
      offset>this.$refs.bar.offsetWidth&&(offset=this.barWidth)
      this.$store.commit('player/setProgress',offset/this.barWidth)
      this.bus.$emit('setCurrentTime')
    },
    startAction(e) {
      this.startX = e.changedTouches[0].clientX - this.position;
      document.ontouchmove = this.moveAction;
      document.ontouchend = this.endAction;
      document.ontouchcancel = this.endAction;
    },
    moveAction(e) {
      let currentX = e.changedTouches[0].clientX;
      this.offsetX = currentX - this.startX;
      if (this.offsetX < 0) {
        this.offsetX = 0;
      } else if (this.offsetX > this.barWidth) {
        this.offsetX = this.barWidth;
      }
      this.$refs.prow.style.width = this.offsetX + "px";
      this.$refs.proc.style.left = this.offsetX + "px";
      this.$store.commit("player/setIsTouch", true);
    },
    endAction() {
      this.position = this.offsetX;
      this.$store.commit("player/setProgress", this.position / this.barWidth);
      this.$store.commit("player/setIsTouch", false);
      this.bus.$emit('setCurrentTime')  //鼠标抬起时修改当前播放时间
      document.ontouchmove = null;
      document.ontouchend = null;
      document.ontouchcancel = null;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/global-style.scss";
.bar {
  width: 70%;
  height: 4px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #666;
  border-radius: 3px;
  @extend .entend_click;
  .pro-w {
    height: 100%;
    background: $theme-color;
    border-radius: 3px;
  }
  .pro-c {
    position: absolute;
    top: 0;
    left: 0;
    width: 10px;
    height: 10px;
    transform: translate(-5px, -5px);
    border-radius: 50%;
    border: 3px solid #fff;
    background: $theme-color;
    @extend .entend_click;
  }
}
</style>
